package com.gzsxy.esjy.client;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import lombok.extern.slf4j.Slf4j;

/**
 * 监测注册中心启动
 * 
 * @author xiaolong
 *
 */
@Configuration
@ConditionalOnProperty(value = "spring.cloud.start-after-eureka", matchIfMissing = false)
@Slf4j
public class StartAfterEurekaServerAutoConfiguration {

	@Value("${eureka.client.service-url.defaultZone}")
	private String aimUrl;

	/**
	 * 重试次数
	 */
	@Value("${spring.cloud.eureka.connected-retry:20}")
	private int connectedRetry;

	/**
	 * 首次延时时间(ms)
	 */
	@Value("${spring.cloud.eureka.retry-dealy:60000}")
	private long retryDelay;

	/**
	 * 延时时间增长指数
	 */
	@Value("${spring.cloud.eureka.dealy-speed:1.1}")
	private double delaySpeed;

	@PostConstruct
	private void init() throws IOException {
		URL url = new URL(aimUrl);
		URLConnection conn = url.openConnection();
		boolean flag = true;
		long time = retryDelay;
		int num = 0;
		while (flag) {
			try {
				conn.connect();
				flag = false;
			} catch (Exception e) {

				if (num >= connectedRetry) {
					throw new IllegalStateException("尝试多次重新连接注册中心失败,请确认该服务是否存在");
				}
				log.warn("检测到注册中心未启动  {}ms后重试     当前进度=[{}/{}]", time, (1 + num++), connectedRetry);

				try {
					Thread.sleep(time);
				} catch (InterruptedException e1) {}
				time *= delaySpeed;
			}
		}
	}
}
